const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const getUserInfo = () => {
  const api = require('./api.js').API;

  return new Promise((resvole, reject) => {
    let info = wx.getStorageSync('info')
    if (info && info !== undefined) {
      resvole(info)
    } else {
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          api.setUserInfo({
            gender: res.userInfo.gender,
            nickName: res.userInfo.nickName,
            avatarUrl: res.userInfo.avatarUrl,
          })
          wx.setStorageSync('info', res.userInfo)
          resvole(res.userInfo)
        }
      })
    }
  })
}


function unique(arr1, key) {
  const res = new Map();
  return arr1.filter((a) => !res.has(a[key]) && res.set(a.from, 1))
}

function genderVerify(info, gender) {
  return new Promise((resolve, reject) => {
    if (info.gender !== gender && gender !== 0) {
      wx.showModal({
        content: gender === 1 ? '只限男生' : '只限女生' + '参与',
        showCancel: false,
        success(res) {
          resolve(false)
        }
      })
      return
    } else {
      resolve(true)
    }
  })
}


function throttle(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500
  }

  let _lastTime = null

  // 返回新的函数
  return function () {
    let _nowTime = +new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments) //将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

module.exports = {
  formatTime,
  getUserInfo,
  throttle,
  genderVerify,
  unique
}